<?php
namespace App\Libs\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 定时器
 */
class AutoController extends Controller
{	


	public function _initialize()
	{   
		header("Content-type: text/html; charset=utf-8");
		set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期
	}


	/**
	 * 发货5天后订单状态更改为已收货
	 * @return [type] [description]
	 */
	public function confirmSh()
	{	
		$dateTime=date("Y-m-d",strtotime("-5 day"));

		$date=date('Y-m-d');

		$logCount=M('auto_log')->where("type=1 and FROM_UNIXTIME(create_time,'%Y-%m-%d')='$date' ")->count();

		if ($logCount) return false; 

		$res=M('orders')->where("order_status=3 and FROM_UNIXTIME(UNIX_TIMESTAMP(order_delivery_time),'%Y-%m-%d') <= '$dateTime' ")->save(array('order_status'=>4));

		$log_res=M('auto_log')->add(array('type'=>1,'create_time'=>time(),'keyword'=>"共计处理 $res 条",'status'=>1));
	}


	/**
	 *  账单逾期
	 *  每天0点后执行
	 */
	public function bill_overdue()
	{
		$time=time();

		$date=date('Y-m-d',$time);

		$logCount=M('auto_log')->where("type=3 and FROM_UNIXTIME(create_time,'%Y-%m-%d')='$date' ")->count();

		//if ($logCount) return false;

		$log_res=M('auto_log')->add(array('type'=>3,'create_time'=>$time,'status'=>0));

        $res=M('order_stages as a')->join("left join orders as b on a.order_id=b.order_id")->field("a.id,a.repayment_time,a.fq_status,b.order_id,b.goods_name,goods_official_price,b.order_status,b.order_comefrom")->where("repayment_time < '$date'  and  fq_status in(1,3) and paid_monthly_rent = 0  and order_status in(3,4,8) ")->select();

        $array=array();

        $num=0;

        foreach ($res as $k => $v) 
        {	
        	// 逾期天数
        	$day=floor((strtotime(date('Y-m-d',$time))-strtotime($v['repayment_time']))/86400);
            
            $arr['days_overdue']=$day;

            $arr['amount_override']=0;

            $strIndex=strpos($v['order_comefrom'],'XCX_ZFB');

            //渠道非支付宝小程序
        	if ($strIndex === false) 
            {
                // 逾期天数大于7天开始算逾期金额
	        	if (($day-7) > 0) 
	        	{
	        		$arr['amount_override']=($v['goods_official_price']*0.003)*($day-7);
	        	}
            }

        	if ($v['fq_status'] == 1) $arr['fq_status']=3;

        	$saveStages=M('order_stages')->where("id='$v[id]'")->save($arr);

        	if ($saveStages) $num+=1;

        	if ($v['order_status'] !=8) 
        	{
        		M('orders')->where("order_id='$v[order_id]'")->save(array('order_status'=>8));
        	}
        }

        M('auto_log')->where("id=$log_res")->save(array('status'=>1,'keyword'=>"共计完成 $num 条"));
	}


	/**
	 *  逾期提醒短信 
	**/
	public function  overdue_warn_sms()
	{		
		$nowTime=date('Y-m-d'); //当前时间
		$nowTime3=date("Y-m-d",strtotime("+3 day")); //当前时间加3天

		$logCount=M('auto_log')->where("type=4 and FROM_UNIXTIME(create_time,'%Y-%m-%d')='$nowTime' ")->count();

	    if ($logCount) return false;

	    $log_res=M('auto_log')->add(array('type'=>4,'create_time'=>time(),'status'=>1));

		$sql="select a.user_phone,a.user_name,a.goods_name,a.order_comefrom,a.order_status,b.repayment_time,b.current_tenancy_term,b.monthly_rent,b.days_overdue,a.zm_order_no from `orders` as a  join 
			(select
				a.current_tenancy_term,((a.monthly_rent+a.goods_installation_charge+a.amount_override)-a.cou_credit_amount) as monthly_rent,a.days_overdue,a.order_id,a.repayment_time from order_stages a
			join (
				select order_id, min(current_tenancy_term) current_tenancy_term from order_stages where  fq_status in (1) and FROM_UNIXTIME(UNIX_TIMESTAMP(repayment_time),'%Y-%m-%d') BETWEEN '$nowTime' and  '$nowTime3' group by order_id
			) b ON a.order_id = b.order_id
			and a.current_tenancy_term = b.current_tenancy_term) as b on a.order_id=b.order_id where a.order_status in('3','4')";

		$res=M()->query($sql);

		foreach ($res as $key => $value) 
		{
			$strIndex=strpos($value['order_comefrom'],'XCX_ZFB');

			//支付宝H5
			if ($value['order_comefrom'] == 'H5_ZFB' ) 
			{
				$str="【绿悦出品】".$value['user_name']."（男士/女士）您好，您在绿悦出品支付宝生活号的".$value['goods_name']."订单，第".$value['current_tenancy_term']."期".$value['monthly_rent']."元，将于".date('Y-m-d',strtotime($value['repayment_time']))."到期。请前往支付宝绿悦出品生活号，支付该期账单。";

				$res=sms_send($value['user_phone'],$str);

			}else if ($strIndex !==false) {
				
				//渠道为支付宝小程序订单
				
				if (date('Y-m-d',strtotime($value['repayment_time'])) == date("Y-m-d",strtotime("+2 day"))) 
				{
					$str="【绿悦出品】尊敬的".$value['user_name']."先生/女士:您好！您的".$value['goods_name']."，第".$value['current_tenancy_term']."期还款金额为".$value['monthly_rent']."元，到期日".date('Y-m-d',strtotime($value['repayment_time']))."，为避免代扣失败，影响您信用，请确保您支付宝还款账户余额充足。";

					$res=sms_send($value['user_phone'],$str);
				}
			}else if($value['order_comefrom'] == 'H5_JD'){
				//渠道为京东H5的订单
				if (!empty($value["zm_order_no"])) 
				{
					//代扣 (提前两天通知)
					if (date('Y-m-d',strtotime($value['repayment_time'])) == date("Y-m-d",strtotime("+2 day"))) 
					{
						$str="【绿悦出品】尊敬的用户:您好！您的".$value['goods_name']."产品，第".$value['current_tenancy_term']."期还款金额为".$value['monthly_rent']."元，到期日".date('Y-m-d',strtotime($value['repayment_time']))."，为了您的信用，请确保您绑定的还款账户余额充足。";
						$res=sms_send($value['user_phone'],$str);
					}
				}else{
					//主动还款
					$str="【绿悦出品】尊敬的用户:您好！您的".$value['goods_name']."产品，第".$value['current_tenancy_term']."期还款金额为".$value['monthly_rent']."元，为了您的信用，请在".date('Y-m-d',strtotime($value['repayment_time']))."之前付款。";
					$res=sms_send($value['user_phone'],$str);
				}
			}			
		}
	}


	/**
	 *  逾期短信
	 *
	 *  每天5点发送逾期短信
	 */
    public function overdue_sms()
    {	
    	$time=time();

		$date=date('Y-m-d',$time);

		$logCount=M('auto_log')->where("type=5 and FROM_UNIXTIME(create_time,'%Y-%m-%d')='$date' ")->count();

		if ($logCount) return false;

		$log_res=M('auto_log')->add(array('type'=>5,'create_time'=>$time,'status'=>1));

    	$sql="select a.user_phone,a.user_name,a.goods_name,a.order_comefrom,b.current_tenancy_term,b.monthly_rent,b.repayment_time,b.days_overdue from `orders` as a  join 
				(select
					a.current_tenancy_term,a.monthly_rent,a.days_overdue,a.repayment_time,a.order_id from order_stages a
				join (
					select order_id, min(current_tenancy_term) current_tenancy_term from order_stages where  fq_status in (3) group by order_id
				) b ON a.order_id = b.order_id
				and a.current_tenancy_term = b.current_tenancy_term) as b on a.order_id=b.order_id where a.order_status=8";

		$res=M()->query($sql);

		foreach ($res as $key => $value) 
		{	
			//支付宝H5
			if ($value['order_comefrom'] == 'H5_ZFB' ) 
			{
				$str="【绿悦出品】".$value['user_name']."（男士/女士）您好，您在绿悦出品支付宝生活号的".$value['goods_name']."订单，第".$value['current_tenancy_term']."期".$value['monthly_rent']."元，已于".date('Y-m-d',strtotime($value['repayment_time']))."到期。请前往支付宝绿悦出品生活号，支付该期账单。";
			    $res=sms_send($value['user_phone'],$str); 

			}else if($value["order_comefrom"] == "H5_JD")
			{  
				$str="【绿悦出品】尊敬的用户，您在京东租用的".$value['goods_name']."，订单多次代扣失败，租金为".$value['monthly_rent']."元。为了您的个人信用，请确保绑定账户余额充足。";
				$res=sms_send($value['user_phone'],$str);
			}
		}

    }



    
    /** 
     *  (支付宝)
     *  查询出需要代扣的账单
     *  每天12点10分 启动定时器
     */
    public function xcx_dk_data($day='kong')
    {	

    	header("Content-type: text/html; charset=utf-8");

    	$nowTime=date('Y-m-d');

        if($day!='kong'){
            $nowTime = $day;
            $sql="select a.order_comefrom as source,b.id as stages_id,a.order_id,(b.monthly_rent + b.goods_installation_charge+b.order_goods_insurance - cou_credit_amount) as money from orders as a left join order_stages as b on a.order_id = b.order_id where a.order_status in (3, 4, 8) and b.order_stages_pay in (1,3) and b.fq_status in (1,3) and FROM_UNIXTIME(UNIX_TIMESTAMP(b.repayment_time),'%Y-%m-%d') = '$nowTime' ";
        }else{
            $sql="select a.order_comefrom as source,b.id as stages_id,a.order_id,(b.monthly_rent + b.goods_installation_charge+b.order_goods_insurance - cou_credit_amount) as money from orders as a left join order_stages as b on a.order_id = b.order_id where a.order_status in (3, 4, 8) and b.order_stages_pay in (1,3) and b.fq_status in (1,3) and FROM_UNIXTIME(UNIX_TIMESTAMP(b.repayment_time),'%Y-%m-%d') = '$nowTime' ";
        }
		$res=M()->query($sql);

        //排除掉 pay_dk_bill 里已经有的stages_id
        $stages_id_arr = $this->varify_stages_id($res);
		foreach ($res as $key => $value) 
		{
			$res[$key]['create_time']=date('Y-m-d H:i:s');

	    	if(strpos($value['source'],'XCX_ZFB') !==false)
	    	{
	    		$res[$key]['source']='XCX_ZFB';
	    	}
	    	if(isset($stages_id_arr[$value['stages_id']])){
	    	    unset($res[$key]);
            }
		}
		if(!empty($res)){
            $log_res=M('auto_log')->add(array('type'=>2,'create_time'=>time(),'status'=>1));
            $add_res=M('pay_dk_bill')->addAll($res);
        }
		return $add_res;
    }
    //返回已经存在的stages_id 数组
    private function varify_stages_id($arr = [])
    {
        if(empty($arr)){
            return [];
        }
        $stage_id_array = array_column($arr,'stages_id');
        $stage_id_str = implode("','",$stage_id_array);
        $pay_dk_bill_data = M('pay_dk_bill')->query("select stages_id from pay_dk_bill where stages_id in ('$stage_id_str')");
        $pay_dk_bill_data = !empty($pay_dk_bill_data)? array_column($pay_dk_bill_data,'stages_id','stages_id'): $pay_dk_bill_data;
        return $pay_dk_bill_data;
    }

    /**
     * 账单发起代扣 (支付宝)
     */
    public function xcx_dk()
    {	
    	$res=M('pay_dk_bill')->where("source='XCX_ZFB' and dk_status in (0,1)")->select();

    	$time=date('Y-m-d H:i:s');

    	if($res)
    	{
	    	$OutApi=A('OutApi/Zhima');

	    	foreach ($res as $key => $v) 
	    	{
	    		$stages=M("order_stages")->where("id='$v[stages_id]' and fq_status in(1,3) ")->field("tenancy_term,current_tenancy_term")->find();

	    		$orders_res=M('orders')->where("order_id='$v[order_id]'  and order_status in(3,4,8) ")->field("goods_name,user_phone,zm_order_no")->find();
	    		
	    		if ($stages && $orders_res["zm_order_no"]) 
	    		{

	    			if ($stages['tenancy_term'] == $stages['current_tenancy_term']) 
	    			{
	    				/*
		    			 *  订单完结(FINISH)  商户订单号 芝麻订单号  资金单号(分期表ID)  金额
		    			 */
	    				$res_pay=$OutApi->credit_pay('FINISH',$v['order_id'],$orders_res["zm_order_no"],$v['stages_id'],$v['money']);

	    			}else{
	    				/*
		    			 *  分期扣款(INSTALLMENT)  商户订单号 芝麻订单号  资金单号(分期表ID)  金额
		    			 */
	    				$res_pay=$OutApi->credit_pay('INSTALLMENT',$v['order_id'],$orders_res["zm_order_no"],$v['stages_id'],$v['money']);
	    			}
	    			
	    			if ($res_pay ==false) 
	    			{
	    				M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>1,'last_time'=>$time,'keyword'=>'扣款失败'));    					
	    			}else{

	    				if ($res_pay['pay_status'] == 'PAY_SUCCESS') 
	    				{

	    					M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>2,'last_time'=>$time,'keyword'=>'支付成功'));
	    				}else{
	    					M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>1,'last_time'=>$time,'keyword'=>$res_pay['message']));
	    				}
	    			}
	    		}
	    	}
    	}
    }


     /**
     * 账单发起代扣  (京东)
     */
    public function jd_dk()
    {
    	$res=M('pay_dk_bill')->where(" source='H5_JD' and dk_status in (0,1)")->select();
    	
    	$time=date('Y-m-d H:i:s');

    	if($res)
    	{
	    	$OutApi=A('OutApi/JdDk');

	    	foreach ($res as $key => $v) 
	    	{
	    		$stages=M("order_stages")->where("id='$v[stages_id]' and fq_status in(1,3) ")->field("tenancy_term,current_tenancy_term")->find();

	    		$zm_order_no=M('orders')->where("order_id='$v[order_id]' and order_comefrom='H5_JD' and order_status in(3,4,8) ")->getField('zm_order_no');
	    		
	    		if ($stages) 
	    		{
		    		if (!$zm_order_no)
		    		{
		    			M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>0,'last_time'=>$time,'keyword'=>'取消代扣协议'));
		    		}else{  
		    			$res_pay=$OutApi->cut_payment($v['stages_id'],$zm_order_no,$v['money']);

		    			if (!$res_pay['payStatus'])
	    				{	
	    					$order_stages_id_new=build_order_no();

	    					M("order_stages")->where("id='$v[stages_id]'")->save(array("id"=>$order_stages_id_new));

	    					M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array("stages_id"=>$order_stages_id_new,'dk_status'=>1,'last_time'=>$time,'keyword'=>$res_pay['data']['response_message'].",原定单号:".$v["stages_id"]));
	    				}else{
	    					M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>2,'last_time'=>$time,'keyword'=>$res_pay['msg']));
	    				}	    	
	    			}
		    	}
	    	}
    	}
    }


    /**
    * 账单发起代扣  (支付宝-花呗)
    */
    public function hb_dk()
    {
    	$res=M('pay_dk_bill')->where(" source='H5_ZFB_HB' and dk_status in (0,1)")->select();
    	
    	$time=date('Y-m-d H:i:s');

    	$out_trade_no=build_order_no();

    	if($res)
    	{
	    	$OutApi=A('OutApi/AlFund');

	    	foreach ($res as $key => $v) 
	    	{
	    		$stages=M("order_stages")->where("id='$v[stages_id]' and fq_status in(1,3) ")->field("tenancy_term,current_tenancy_term")->find();

	    		$count=M('orders')->where("order_id='$v[order_id]' and order_comefrom='H5_ZFB_HB' and order_status in(3,4,8) ")->count();
	    		
	    		if ($stages) 
	    		{ 
		    		if ($count)
		    		{ 
		    			$row=M("hb_dj")->where("out_order_no='$v[order_id]'")->field("auth_no,yb_payer_user_id")->find();
		    			
		    			if($row)
		    			{
		    				$res_pay=$OutApi->pay($out_trade_no,$v['money'],$row["yb_payer_user_id"],$row["auth_no"]);
		    				
		    				if ("ORDER_SUCCESS_PAY_SUCCESS" == $res_pay['result_code']) 
							{
								//扣款成功 修改log表状态
		    					M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>2,'last_time'=>$time,'keyword'=>$res_pay['result_code'],'out_trade_no'=>$out_trade_no));
                                $log = [];
		    					$log['log']=json_encode($res_pay);
                                $log['create_time']=date("Y-m-d H:i:s");
                                $log['keyword']='花呗h5订单扣款成更之后实时返回';
		    					M('log_xyjh')->add($log);
		    					M("order_stages")->where("id='$v[stages_id]'")->save(array("out_order_id"=>$out_trade_no));	
							}else{
								M('pay_dk_bill')->where("stages_id='$v[stages_id]'")->save(array('dk_status'=>1,'last_time'=>$time,'keyword'=>$res_pay['result_code']."：".$res_pay['display_message']));
							}
		    			}   	
	    			}
		    	}
	    	}
    	}
    }



 




}